import { ref, h } from 'vue';
import type { DataTableColumns } from 'naive-ui';
import { NInput, NSelect, NText } from 'naive-ui';
import { insertData } from '@/service';
import { calMinutesBetweenTimes, getCurrentTime } from '@/utils';
import type { RowData, TimeInfo, selectOption } from './type';

export const nullFormValue = {
  name: '',
  type: ''
};

export const objectType: selectOption[] = [
  {
    label: '拖延',
    value: '拖延'
  },
  {
    label: '杂事',
    value: '杂事'
  },
  {
    label: '学习',
    value: '学习'
  },
  {
    label: '正事',
    value: '正事'
  },
  {
    label: '正常生活',
    value: '正常生活'
  }
];

export const createData = (): RowData[] => [
  {
    key: 0,
    name: '',
    range: [],
    type: '',
    duration: ''
  },
  {
    key: 1,
    name: '',
    range: [],
    type: '',
    duration: ''
  },
  {
    key: 2,
    name: '',
    range: [],
    type: '',
    duration: ''
  },
  {
    key: 3,
    name: '',
    range: [],
    type: '',
    duration: ''
  },
  {
    key: 4,
    name: '',
    range: [],
    type: '',
    duration: ''
  },
  {
    key: 5,
    name: '',
    range: [],
    type: '',
    duration: ''
  },
  {
    key: 6,
    name: '',
    range: [],
    type: '',
    duration: ''
  },
  {
    key: 7,
    name: '',
    range: [],
    type: '',
    duration: ''
  },
  {
    key: 8,
    name: '',
    range: [],
    type: '',
    duration: ''
  },
  {
    key: 9,
    name: '',
    range: [],
    type: '',
    duration: ''
  },
  {
    key: 10,
    name: '',
    range: [],
    type: '',
    duration: ''
  }
];

const STORAGE_KEY = 'time_records';

export const getTodayData = (value?: number) => {
  const now = value ? new Date(value) : new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

const today = getTodayData();

export const storeKey = STORAGE_KEY + today;

const storeValue = JSON.parse(window.localStorage.getItem(storeKey)!);

export const data = ref(storeValue === null ? createData() : storeValue);

export const storeData = () => {
  localStorage.setItem(storeKey, JSON.stringify(data.value));
};

export const clearData = () => {
  data.value = createData();
  localStorage.removeItem(storeKey);
};

export const startTask = () => {
  data.value[0].range[0] = getCurrentTime();
  storeData();
};

/**
 * 先保存数据到后端
 * 再清空缓存 + 数据
 */
export const insert = async (now: string) => {
  const back_data: TimeInfo[] = [];
  if (data.value) {
    let item: RowData;
    for (item of data.value) {
      const matchResult = item.duration.match(/\d+/);
      let cur_duration;
      if (matchResult !== null) {
        cur_duration = parseInt(matchResult[0], 10);
      } else {
        cur_duration = 0;
      }
      if (item.name !== '') {
        back_data.push({
          name: item.name,
          begin: item.range[0],
          end: item.range[1],
          tag: item.type,
          duration: cur_duration
        });
      }
    }
  }
  const result = await insertData(back_data, now);
  if (!result.error) {
    clearData();
    window.$message?.success('保存成功！');
  }
};

const createColumns = (): DataTableColumns<RowData> => [
  {
    title: '活动名称',
    key: 'name',
    align: 'center',
    render(row, index) {
      return h(NInput, {
        value: row.name,
        onUpdateValue(v) {
          data.value[index].name = v;
          storeData();
        }
      });
    }
  },
  {
    title: '活动时间',
    align: 'center',
    key: 'range',
    render(row, index) {
      return h(NInput, {
        pair: true,
        separator: '-',
        value: row.range,
        onUpdateValue(v: string[]) {
          data.value[index].range = v;
          data.value[index].duration = `${calMinutesBetweenTimes(v[0], v[1])} min`;
          data.value[index + 1].range[0] = v[1];
          storeData();
        }
      });
    }
  },
  {
    title: '活动类别',
    align: 'center',
    key: 'type',
    render(row, index) {
      return h(NSelect, {
        value: row.type,
        options: objectType,
        onUpdateValue(v: string) {
          data.value[index].type = v;
          storeData();
        }
      });
    }
  },
  {
    title: '间隔时间',
    align: 'center',
    key: 'duration',
    render(row, index) {
      return h(NText, row.duration);
    }
  }
];
export const columns = createColumns();
export const pagination = {
  pageSize: 10
};

const intiValue = -1;
/**
 * 完成任务
 * 	找到range[0]有的，[1]没有的
 */
export const finishTask = () => {
  let index = intiValue;
  for (let i = 0; i < data.value.length; i++) {
    if (data.value[i].range[0] && !data.value[i].range[1]) {
      index = i;
    }
  }
  if (index === intiValue || index >= data.value.length) {
    window.$dialog?.warning({
      title: '提示',
      content: '当前表格数据已满，请先进行保存',
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: async () => {
        await insert();
        startTask();
      }
    });
    return -1;
  }
  data.value[index].range[1] = getCurrentTime();
  data.value[index].duration = `${calMinutesBetweenTimes(data.value[index].range[0], data.value[index].range[1])} min`;

  data.value[index + 1].range[0] = getCurrentTime();
  storeData();

  return index;
};

const prefix = '```mermaid\n';
const suffix = '\n```';

export const createGanttCode = () => {
  let ganttChart = `${prefix}gantt\n`;
  ganttChart += '    dateFormat  HH:mm\n';
  ganttChart += '    axisFormat  %H:%M\n';
  ganttChart += '    title 甘特图\n\n';
  ganttChart += '    section 任务\n';

  data.value.forEach(task => {
    const name = task.name || '';
    const range = task.range.length > 0 ? `${task.range[0]}, ${task.range[1]}` : '';
    if (name !== '' && range !== '') {
      ganttChart += `    ${name}             : ${range}\n`;
    }
  });

  return ganttChart + suffix;
};

export const createPieCode = () => {
  let pieChart = `${prefix}pie\n`;
  pieChart += '    title 任务分布\n';

  const taskDurations = {};
  data.value.forEach(task => {
    const type = task.type || '';
    const duration = task.duration || '';
    if (type !== '' && duration !== '') {
      const minutes = parseInt(duration.split(' ')[0]);
      if (taskDurations.hasOwnProperty(type)) {
        taskDurations[type] += minutes;
      } else {
        taskDurations[type] = minutes;
      }
    }
  });

  Object.keys(taskDurations).forEach(type => {
    const duration = taskDurations[type];
    pieChart += `    "${type}" : ${duration}\n`;
  });

  return pieChart + suffix;
};
